﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;
using System.Net.Sockets;
using System.Timers;

namespace WuHouCiClient
{
    class CRecvSendPackageThreadCreator
    {
        private static CRecvSendPackageThreadCreator instance = null;
        private static bool isCreateThread = false;
        private CRecvSendPackageThreadCreator() { }
        public static CRecvSendPackageThreadCreator getInstance()
        {
            if (instance == null)
            {
                lock (instance)
                {
                    if (instance == null)
                    {
                        instance = new CRecvSendPackageThreadCreator();
                    }
                }
            }
            return instance;
        }
        /////////////
        public bool CreateThread()
        {
            if (isCreateThread == false)
            {
                ///创建底层收发信息线程。
                Thread main_loop_th = new Thread(send_recv_package_main_loop);
                main_loop_th.Start();
                //--------------------------
                isCreateThread = true;
                return true;
            }
            else
            {
                return false;
            }
        }
        public void send_recv_package_main_loop()
        {
            //创建链接，
            client_config cconfig = new client_config();
            string ip = cconfig.getIP();
            int port = cconfig.getPort();
            int index = 1;
        flag: Console.WriteLine(ip);
            Console.WriteLine(port);

            TcpClient clientSocket = CNet.createConnect(ip, port);

            if (clientSocket == null)
            {
                Console.WriteLine("connect error!");
                if (index <= 30)
                {
                    index++;
                    Thread.Sleep(1000);
                    goto flag;
                }
                else
                {
                    Console.WriteLine("reconnect end!  connect failed----");
                    return;
                }
            }
            CProtocol cprotocol = CProtocol.getInstance(clientSocket);
            while (true)
            {
                int readNum = 0;
                byte[] message = CNet.recvPackage(ref readNum, clientSocket);
                if (message.Length > 0)
                {
                    cprotocol.pushRecvBuffer(message);
                }
            }
        }
    }
}
